package cn.wolfcode.trip.admin.web.controller;

import cn.wolfcode.trip.admin.web.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.util.HashMap;
import java.util.Map;

@Controller
public class ImageController {

    @Autowired
    private ServletContext ctx;


    @ResponseBody
    @RequestMapping("/upload")
    public Object updateImage(MultipartFile upload) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        try {
            //通过服务器域对象获取相对项目路径
            String imagePath = UploadUtil.upload(upload, UploadUtil.IMG_PATH + "/upload");

            map.put("uploaded", 1);
            map.put("url", imagePath);

        } catch (Exception e) {
            e.printStackTrace();
            Map<String,Object> error = new HashMap<String, Object>();
            error.put("errorMessage",e.getMessage());
            map.put("uploaded", 0);
            map.put("error", error);

        }

        return map;
    }


}
